// component/index/tips/worktime.js
const app = getApp();

var events = require('events');

Component({
    "options": {
        styleIsolation: 'isolated'
    },
    /**
     * 组件的属性列表
     */
    properties: {
        data: {type: Object, value: null},
        templateid: {type: Number, value: null},
        show: {type: Boolean, value: false}
    },

    /**
     * 组件的初始数据
     */
    data: {
        images: [],
        percent: 0,
        finished: false,
        stoped: false,
    },

    lifetimes: {
        attached() {
            this.event = new events.EventEmitter();
            this.promise = app.func.resolve([])
                .then(() => {
                    return app.func.postPromise('/v2/coupon/preview/' + this.data.templateid, this.data.data)
                        .then(([code, res]) => {
                            if (code == 200) {
                                return {urls: res.data, images: []};
                            } else {
                                this.setData({
                                    finished: true,
                                });
                                return {urls: [], images: []};
                            }
                        }, () => {
                            return {urls: [], images: []};
                        });
                });
        },
        detached() {
            this.data.stoped = true;
            this.event.emit('stop');
            this.promise.then((res) => {
                var images = res.images;
                console.log("delete images~~~");
                console.log(images);
                for (let i = 0; i < images.length; i++) {
                    wx.getFileSystemManager().unlinkSync(images[i]);
                }
            });
        },
        ready: function () {

        }
    },

    observers: {
        "show": function (show) {
            if (!show) {
                return;
            }
            this.promise = this.promise.then((res) => {
                let urls = res.urls;
                let result = app.func.resolve(res.images);
                let onePercent = 100 / urls.length;
                for (let i = 0; i < urls.length; i++) {
                    let url = urls[i];
                    result = result.then((images) => {
                        return app.func.getPromise(url)
                            .then(([code, res]) => {
                                if(code == 200) {
                                    let imageres = res.data;
                                    return app.func.promise((resolve, reject) => {
                                        if (this.data.stoped) {
                                            resolve(images);
                                        }
                                        console.log(url);
                                        let task = wx.downloadFile({
                                            url: imageres,
                                            success: (res) => {
                                                images.push(res.tempFilePath);
                                                resolve(images);
                                            },
                                            fail: () => {
                                                resolve(images);
                                            },
                                            complete: () => {
                                                this.event.removeAllListeners('stop');
                                            }
                                        });
                                        this.event.once('stop', () => {
                                            task.abort();
                                        });
                                        task.onHeadersReceived((res) => {
                                            console.log(res);
                                            this.setData({
                                                percent: Math.round(onePercent * i + onePercent / 10)
                                            });
                                        });
                                        task.onProgressUpdate((res) => {
                                            if (res.totalBytesExpectedToWrite != null) {
                                                let percent = onePercent * i + onePercent / 10;
                                                percent = percent + onePercent * 0.9 * (res.totalBytesWritten / res.totalBytesExpectedToWrite);
                                                this.setData({
                                                    percent: Math.round(percent)
                                                });
                                            }
                                        })
                                    });
                                } else {
                                    return images;
                                }
                            }).catch((error) => {
                                console.error(error);
                                return images;
                            });
                    });
                }
                return result.then((images) => {
                    this.setData({
                        images: images,
                        finished: true
                    });
                    return {urls: [], images: images};
                });
            });
        }
    },

    /**
     * 组件的方法列表
     */
    methods: {
        close: function () {
            this.triggerEvent('close');
        },
        preview: function (e) {
            let images = this.data.images;
            let index = e.currentTarget.dataset.index;
            let current = images[index];
            wx.previewImage({
                current: current,
                urls: images
            })
        },
    }
})
